package com.snpic.appaw.module.infra.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.snpic.appaw.framework.common.constants.SystemConstant;

import com.snpic.appaw.module.infra.dal.dataobject.config.PwbConfigDO;
import com.snpic.appaw.module.infra.dal.mysql.config.PwbConfigMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.snpic.appaw.module.infra.enums.InfraConstant.SN_CONFIG_KEY;


/**
 * @description 配置信息工具类，使用静态方法管理配置
 * 从数据表pwb_config中读取配置信息到本地
 */
@Component("configInfo")
@Slf4j
public class ConfigInfo {
	@Autowired
	PwbConfigMapper pwbConfigMapper;

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

//	private static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
	/**
	 * 获取配置参数
	 */
//	public static String getByProperties(String name) {
//		return map.get(name);
//	}

	public String getConfigValue(String name) {
		Object value = redisTemplate.opsForHash().get(SN_CONFIG_KEY, name);
		return value != null ? ((String) value).split("\\|")[0] : null;
	}

	/**
	 * Spring启动后一秒执行,之后每300秒执行一次
	 */
	@Scheduled(initialDelay = 1000, fixedRate = 300 * 1000)
	public void loadResource() {
		log.info("加载系统配置,读取数据表pwb_config,存储到Reids");
		List<PwbConfigDO> pwbConfigs = pwbConfigMapper.selectList(
			Wrappers.<PwbConfigDO>lambdaQuery().eq(PwbConfigDO::getStatus, SystemConstant.StrOne)
		);

//		map.clear();
//		for (int i = 0; i < pwbConfigs.size(); i++) {
//			map.put(pwbConfigs.get(i).getConfigCode(), pwbConfigs.get(i).getConfigValue());
//			map.put(pwbConfigs.get(i).getConfigCode() + "IsExpect", pwbConfigs.get(i).getIsExpect());
//		}
		// 存储到Redis Hash
		Map<String, String> configMap = pwbConfigs.stream()
			.collect(Collectors.toMap(
				PwbConfigDO::getConfigCode,
				p -> p.getConfigValue() + "|" + p.getIsExpect()
			));

		redisTemplate.opsForHash().putAll(SN_CONFIG_KEY, configMap);
	}
}